layui.use(['table', 'admin', 'ax', 'func', 'laydate','layer', 'form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;
    var layer = layui.layer;
    var form = layui.form;

    /**
     * 财务罚款管理
     */
    var BtyCwFine = {
        tableId: "btyCwFineTable"
    };

    //渲染时间选择框
    laydate.render({
        elem: '#month',
        format:'yyyy-MM',
        value:new Date().getMonth() == '0' ? new Date().getFullYear() - 1 + "-" + 12 : (new Date().getMonth() < 10 ? new Date().getFullYear() + "-0" + new Date().getMonth() : new Date().getFullYear() + "-" + new Date().getMonth()),//默认上个月
        type: 'month',
        done:function(value,date,startDate){
        }
    });

    /**
     * 检索店名
     */
    var languageAjax = new $ax(Feng.ctxPath + "/btyCwFine/dmList");
    var languageResult = languageAjax.start();
    $.each(languageResult.data, function (index, val) {
        $("#dm").append("<option value='" + val.dm + "'>" + val.dm + "</option>");
    });
    form.render('select');

    /**
     * 同步店名
     */
    form.on('submit(btnSyn)', function (data) {
        BtyGoodsbtnSyn();
    });

    var loadIndex;
    BtyGoodsbtnSyn = function(){
        if ($('#month').val() == "") {
            Feng.error("请选择月份");
            return;
        }
        loadIndex = layer.load('正在同步...',2, { shade: [0.15, '#ccc'] });
        setTimeout(()=>{
            var ajax = new $ax(Feng.ctxPath + "/btyCwFine/synData", function (data) {
                if (data.code == 1) {
                    Feng.error("初始化数据失败!" + data.message);
                    layer.close(loadIndex);
                    return;
                }
                Feng.success("初始化数据成功！");
                layer.close(loadIndex);
                table.reload(BtyCwFine.tableId);

            }, function (data) {
                Feng.error("添加失败！" + data.responseJSON.message);
                layer.close(loadIndex);
            });
            ajax.set("month", $("#month").val());
            ajax.start();
            return false;
        },100)
    };

    /**
     * 批量审核
     */
    form.on('submit(btnAudit)', function (data) {
        BtyCwFinebtnAudit();
    });

    BtyCwFinebtnAudit = function(){
        if ($('#month').val() == "") {
            Feng.error("请选择月份");
            return;
        }
        loadIndex = layer.load('正在同步...',2, { shade: [0.15, '#ccc'] });
        setTimeout(()=>{
            var ajax = new $ax(Feng.ctxPath + "/btyCwFine/batchAudit", function (data) {
                if (data.code == 201) {
                    Feng.error("初始化数据失败!" + data.message);
                    layer.close(loadIndex);
                    return;
                }
                Feng.success("有罚款和罚款人的门店，已审核成功！");
                layer.close(loadIndex);
                table.reload(BtyCwFine.tableId);

            }, function (data) {
                Feng.error("初始化数据失败!" + data.responseJSON.message);
                layer.close(loadIndex);
            });
            ajax.set("month", $("#month").val());
            ajax.start();
            return false;
        },100)
    };

    /**
     * 同步到货赔审核
     */
    form.on('submit(synGoodspay)', function (data) {
        BtyCwFinesynGoodspay();
    });

    BtyCwFinesynGoodspay = function(){
        if ($('#month').val() == "") {
            Feng.error("请选择月份");
            return;
        }
        loadIndex = layer.load('正在同步...',2, { shade: [0.15, '#ccc'] });
        setTimeout(()=>{
            var ajax = new $ax(Feng.ctxPath + "/btyCwFine/synGoodspay", function (data) {
                if (data.code == 201) {
                    Feng.error(data.message);
                    layer.close(loadIndex);
                    return;
                }
                Feng.success("同步成功，罚款已同步到货赔审核中！");
                layer.close(loadIndex);
                table.reload(BtyCwFine.tableId);

            }, function (data) {
                Feng.error("同步失败!" + data.responseJSON.message);
                layer.close(loadIndex);
            });
            ajax.set("month", $("#month").val());
            ajax.start();
            return false;
        },100)
    };

    /**
     * 初始化表格的列
     */
    BtyCwFine.initColumn = function () {
        return [[
            // {type: 'checkbox'},
            {type: 'numbers',align:'center', title: '序号'},
            {field: 'id', hide: true, title: ''},
            // {field: 'cwry', sort: true, title: '财务人员'},
            {field: 'dm', title: '店名'},
            {field: 'yaoma', title: '妖码', width: 100},
            {field: 'cwm', title: '编码', width: 80},
            {field: 'shopownerView', title: '店长', width: 100},
            {field: 'mobile', title: '店长手机'},
            {field: 'cwDeduction', title: '财务罚款', edit: 'text', event: 'fine'},
            {field: 'month', title: '月份'},
            {field: 'dzName', title: '罚款人', edit: 'text', event: 'setdz'},
            {field: 'status', title: '状态',templet:function (d) {
                    if(d.status==0){
                        return '待审核';
                    }else if (d.status==1){
                        return '通过';
                    }else if (d.status==2){
                        return '已同步货赔';
                    }else {
                        return '';
                    }
             }},
            {field: 'isCompliance', title: '是否合规',templet:function (d) {
                if(d.isCompliance === 0) {
                    return '合规';
                } else if (d.isCompliance === 1) {
                    return '不合规';
                } else {
                    return '不合规';
                }
            }},

            // {field: 'mdbh', sort: true, title: '门店编号-对应bty_brand表bh'},
            // {field: 'remark', sort: true, title: '备注'},


            {align: 'center', toolbar: '#tableBar', title: '操作'}
        ]];
    };

    //监听单元格编辑
    table.on('edit(btyCwFineTable)', function (obj) {
        var value = obj.value, //得到修改后的值
            data = obj.data, //得到所在行所有键值
            field = obj.field; //得到字段

        var selector = obj.tr.selector + ' td[data-field="' + obj.field + '"] div';
        var oldtext = $(selector).text();

        if (data.status == 1) {
            layer.msg('已经通过货赔审核，不能再修改数据！', {icon: 4},);
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }else if (data.status == 2) {
            layer.msg('已经同步货赔，不能再修改数据！', {icon: 4},);
            $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
            return false;
        }

        if (field == "cwDeduction") {
            if (Math.floor(value) != value || value > 0){
                Feng.error("修改失败，只允许输入0或负整数");
                $(obj.tr.selector + ' td[data-field="' + obj.field + '"] input').val(oldtext);
                return false;
            }
        }

        $.ajax({
            type: "GET",
            url: "/btyCwFine/editById",
            datatype: "json",
            data: data,
            success: function (data) {

            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) {
            }
        });
    });

    /**
     * 点击查询按钮
     */
    var queryData = {};
    BtyCwFine.search = function () {
        queryData['dm'] = $("#dm").val();
        queryData['month'] = $("#month").val();
        queryData['status'] = $("#status").val();
        queryData['isCompliance'] = $("#isCompliance").val();

        table.reload(BtyCwFine.tableId, {
            where: queryData, page: {curr: 1}
        });
    };

    /**
     * 弹出添加对话框
     */
    BtyCwFine.openAddDlg = function () {
        func.open({
            title: '添加财务罚款',
            content: Feng.ctxPath + '/btyCwFine/add',
            tableId: BtyCwFine.tableId
        });
    };

     /**
      * 通过
      *
      * @param data 点击按钮时候的行数据
      */
      BtyCwFine.openEditDlg = function (data) {
          var operation = function () {
              var ajax = new $ax(Feng.ctxPath + "/btyCwFine/audit", function (data) {
                  if (data.code == 201) {
                      Feng.error("通过失败!" + data.message);
                      layer.close(loadIndex);
                      return;
                  }
                  Feng.success("通过成功!");
                  table.reload(BtyCwFine.tableId);
              }, function (data) {
                  Feng.error("通过失败!" + data.message + "!");
              });
              ajax.set("id", data.id);
              ajax.start();
          };
          Feng.confirm("是否确认通过?", operation);
      };


    /**
     * 导出excel按钮
     */
    BtyCwFine.exportExcel = function () {
        var checkRows = table.checkStatus(BtyCwFine.tableId);
        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }
    };

    /**
     * 点击撤回
     *
     * @param data 点击按钮时候的行数据
     */
    BtyCwFine.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/btyCwFine/recall", function (data) {
                if (data.code == 201) {
                    Feng.error("撤回失败!" + data.message);
                    layer.close(loadIndex);
                    return;
                }
                Feng.success("撤回成功!");
                table.reload(BtyCwFine.tableId);
            }, function (data) {
                Feng.error("撤回失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("<div style='font-size: 16px; color: #D9001B;text-align: center'>是否撤回?</div>" +
            "<div style='color: #F59A23; font-size: 12px'>每月10号前可撤回通过的，与已同步货赔的数据，撤回后可重新修改财务罚款</div>", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + BtyCwFine.tableId,
        url: Feng.ctxPath + '/btyCwFine/list',
        page: true,
        limit: 20,
        height: "full-59",
        cellMinWidth: 100,
        where: {month:new Date().getMonth() == '0' ? new Date().getFullYear() - 1 + "-" + 12 : (new Date().getMonth() < 10 ? new Date().getFullYear() + "-0" + new Date().getMonth() : new Date().getFullYear() + "-" + new Date().getMonth())},//默认上个月
        cols: BtyCwFine.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BtyCwFine.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {

    BtyCwFine.openAddDlg();

    });

    // 导出excel
    $('#btnExp').click(function () {
        BtyCwFine.exportExcel();
    });

    /**
     * 选择罚款人
     * @param data
     */
    BtyCwFine.selDz = function (obj, data) {
        var url = Feng.ctxPath + '/btyCwFine/selectDz?id=' + data.id + "&yaoma=" + data.yaoma;

        layer.open({
            type: 2,
            title: '选择罚款人门店：' + data.dm,
            area: ['350px', '510px'],
            content: url,
            end: function () {
                //获取详情信息，填充表单
                var ajax = new $ax(Feng.ctxPath + "/btyCwFine/detail?id=" + data.id);
                var result = ajax.start();
                obj.update({
                    dzName: result.data.dzName
                });
            },
            cancel: function (index) {
            }
        });
    };

    // 工具条点击事件
    table.on('tool(' + BtyCwFine.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            BtyCwFine.openEditDlg(data);
        } else if (layEvent === 'delete') {
            BtyCwFine.onDeleteItem(data);
        } else if (layEvent === 'setdz') {
            if (data.status == 0) {
                BtyCwFine.selDz(obj, data);
            }else {
                layer.msg('待审核状态才可修改罚款人！', {icon: 4},);
                return false;
            }

        }else if (layEvent === 'fine'){
            if (data.status != 0){
                layer.msg('待审核状态才可修改财务罚款！', {icon: 4},);
                return false;
            }
        }
    });
});
